package in.hitmedia.test.sort;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MergeSort 
{

	private Long[] read(String filename) throws IOException
	{
		
		BufferedReader br = new BufferedReader(new FileReader(filename));
		
		String line = null;
		
		List<Long> a = new ArrayList<Long>();
		while((line = br.readLine()) != null)
		{
			try
			{
				long parseLong = Long.parseLong(line.trim());
				a.add(parseLong);
			}
			catch (NumberFormatException nfe)
			{
				
			}
		}
		
		return a.toArray(new Long[a.size()]); 
	}
	
	
	private void merge(Long a[], int start, int n, int end)
	{
		//print(a);
		Long newArray[] = new Long [(end-start)+1];
		
		int leftStart = start;
		int leftEnd = n;
		int rightStart = n+1;
		int rightEnd = end;
		
		int i=leftStart;
		int j=rightStart;
		int k=0;
		while (i <= leftEnd && j <= rightEnd)
		{
			if  (a[i] <=  a[j])
			{
				newArray[k]=a[i];
				i++;
			}
			else
			{
				newArray[k]=a[j];
				j++;
			}
			k++;
		}
		
		while (i <= leftEnd)
		{
			newArray[k]=a[i];
			i++;
			k++;
		}
		
		while (j <= rightEnd)
		{
			newArray[k]=a[j];
			j++;
			k++;
		}
		
		System.arraycopy(newArray, 0, a, start, newArray.length);
	}
	
	private void mergeSort(Long a[], int start, int end)
	{
		
		if (start >= end || a == null)
		{
			return;
		}
		//print(a);
		
		if ((end-start)+1 ==2)
		{
			if (a[end] < a[start])
			{
				Long tmp = a[start];
				a[start] = a[end];
				a[end] = tmp; 
			}
		}
		else
		{
			int n = start+(end - start) / 2;
			mergeSort(a, start, n);
			mergeSort(a, n+1, end);
			merge(a, start, n, end);
			
		}
	}
	
	private static void print(Long a[])
	{
		for(int i=0; i < a.length; ++i)
		{
			System.out.print(a[i]+"\t");
			if ((i+1) %10 == 0)
			{
				System.out.println();
			}
		}
		System.out.println();
	}
	
	public void runMergeSort (String in, String out)
	{
		try
		{
			Long[] inArray = read(in);
			
			//Long inArray[] = new Long[] {4L, 8L, 2L , 1L, 9L ,7L};
			//print(inArray);
			
			long start = System.currentTimeMillis();
			
			mergeSort(inArray, 0, inArray.length-1);
			long end = System.currentTimeMillis();
			
			System.out.println("Time to process "+((end - start)) +" miliseconds.");
			
			BufferedWriter bw = new BufferedWriter(new FileWriter(out));
			
			for (int i = 0; i < inArray.length; ++i)
			{
				bw.write(""+inArray[i]);
				bw.newLine();
			}
			bw.close();
			
			//print(inArray);
		}
		catch (Exception e)
		{
			System.out.println("Received exception"+ e);
		}
		
		
	}
	
	public static void main(String args[])
	{
		MergeSort ms = new MergeSort();
		ms.runMergeSort(args[0], args[1]);
	}
	
}
